"""
交易管理模块
"""

import time
import uuid
from typing import Dict, Any, Optional, List
from datetime import datetime


class Transaction:
    """交易类"""
    
    def __init__(self, transaction_id: str, meter_id: str, amount: int, 
                 transaction_type: str = "RECHARGE"):
        """
        初始化交易
        
        Args:
            transaction_id: 交易ID
            meter_id: 表计ID
            amount: 交易金额（分）
            transaction_type: 交易类型
        """
        self.transaction_id = transaction_id
        self.meter_id = meter_id
        self.amount = amount
        self.transaction_type = transaction_type
        self.timestamp = int(time.time())
        self.status = "PENDING"
        self.token = None
        self.error_message = None
        
        # 交易详情
        self.details = {
            'created_at': self.timestamp,
            'updated_at': self.timestamp,
            'operator_id': None,
            'payment_method': None,
            'notes': None
        }
    
    def set_token(self, token: str) -> None:
        """
        设置交易令牌
        
        Args:
            token: 交易令牌
        """
        self.token = token
        self.details['updated_at'] = int(time.time())
    
    def set_status(self, status: str, error_message: Optional[str] = None) -> None:
        """
        设置交易状态
        
        Args:
            status: 新状态
            error_message: 错误信息
        """
        self.status = status
        self.error_message = error_message
        self.details['updated_at'] = int(time.time())
    
    def set_operator(self, operator_id: str) -> None:
        """
        设置操作员
        
        Args:
            operator_id: 操作员ID
        """
        self.details['operator_id'] = operator_id
        self.details['updated_at'] = int(time.time())
    
    def set_payment_method(self, payment_method: str) -> None:
        """
        设置支付方式
        
        Args:
            payment_method: 支付方式
        """
        self.details['payment_method'] = payment_method
        self.details['updated_at'] = int(time.time())
    
    def add_note(self, note: str) -> None:
        """
        添加备注
        
        Args:
            note: 备注内容
        """
        if self.details['notes'] is None:
            self.details['notes'] = []
        self.details['notes'].append({
            'timestamp': int(time.time()),
            'content': note
        })
        self.details['updated_at'] = int(time.time())
    
    def to_dict(self) -> Dict[str, Any]:
        """
        转换为字典
        
        Returns:
            交易字典
        """
        return {
            'transaction_id': self.transaction_id,
            'meter_id': self.meter_id,
            'amount': self.amount,
            'amount_formatted': f"{self.amount / 100:.2f}元",
            'transaction_type': self.transaction_type,
            'timestamp': self.timestamp,
            'status': self.status,
            'token': self.token,
            'error_message': self.error_message,
            'details': self.details
        }
    
    def is_completed(self) -> bool:
        """
        检查交易是否完成
        
        Returns:
            是否完成
        """
        return self.status in ["COMPLETED", "SUCCESS"]
    
    def is_failed(self) -> bool:
        """
        检查交易是否失败
        
        Returns:
            是否失败
        """
        return self.status in ["FAILED", "CANCELLED", "ERROR"]
    
    def is_pending(self) -> bool:
        """
        检查交易是否待处理
        
        Returns:
            是否待处理
        """
        return self.status == "PENDING"


class TransactionManager:
    """交易管理器"""
    
    def __init__(self):
        """初始化交易管理器"""
        self.transactions: Dict[str, Transaction] = {}
        self.transaction_counter = 0
    
    def create_transaction(self, meter_id: str, amount: int, 
                          transaction_type: str = "RECHARGE") -> Transaction:
        """
        创建新交易
        
        Args:
            meter_id: 表计ID
            amount: 交易金额
            transaction_type: 交易类型
            
        Returns:
            新交易实例
        """
        self.transaction_counter += 1
        transaction_id = f"TXN{self.transaction_counter:08d}"
        
        transaction = Transaction(transaction_id, meter_id, amount, transaction_type)
        self.transactions[transaction_id] = transaction
        
        return transaction
    
    def get_transaction(self, transaction_id: str) -> Optional[Transaction]:
        """
        获取交易
        
        Args:
            transaction_id: 交易ID
            
        Returns:
            交易实例
        """
        return self.transactions.get(transaction_id)
    
    def get_transactions_by_meter(self, meter_id: str, 
                                 limit: int = 50) -> List[Transaction]:
        """
        获取指定表计的交易
        
        Args:
            meter_id: 表计ID
            limit: 返回数量限制
            
        Returns:
            交易列表
        """
        meter_transactions = [
            txn for txn in self.transactions.values()
            if txn.meter_id == meter_id
        ]
        
        # 按时间倒序排列
        meter_transactions.sort(key=lambda x: x.timestamp, reverse=True)
        
        return meter_transactions[:limit]
    
    def get_transactions_by_status(self, status: str, 
                                  limit: int = 50) -> List[Transaction]:
        """
        获取指定状态的交易
        
        Args:
            status: 交易状态
            limit: 返回数量限制
            
        Returns:
            交易列表
        """
        status_transactions = [
            txn for txn in self.transactions.values()
            if txn.status == status
        ]
        
        # 按时间倒序排列
        status_transactions.sort(key=lambda x: x.timestamp, reverse=True)
        
        return status_transactions[:limit]
    
    def get_recent_transactions(self, hours: int = 24, 
                               limit: int = 100) -> List[Transaction]:
        """
        获取最近的交易
        
        Args:
            hours: 时间范围（小时）
            limit: 返回数量限制
            
        Returns:
            交易列表
        """
        cutoff_time = int(time.time()) - (hours * 3600)
        
        recent_transactions = [
            txn for txn in self.transactions.values()
            if txn.timestamp >= cutoff_time
        ]
        
        # 按时间倒序排列
        recent_transactions.sort(key=lambda x: x.timestamp, reverse=True)
        
        return recent_transactions[:limit]
    
    def get_transaction_statistics(self, hours: int = 24) -> Dict[str, Any]:
        """
        获取交易统计
        
        Args:
            hours: 统计时间范围（小时）
            
        Returns:
            统计信息
        """
        cutoff_time = int(time.time()) - (hours * 3600)
        
        recent_transactions = [
            txn for txn in self.transactions.values()
            if txn.timestamp >= cutoff_time
        ]
        
        total_transactions = len(recent_transactions)
        completed_transactions = len([txn for txn in recent_transactions if txn.is_completed()])
        failed_transactions = len([txn for txn in recent_transactions if txn.is_failed()])
        pending_transactions = len([txn for txn in recent_transactions if txn.is_pending()])
        
        total_amount = sum(txn.amount for txn in recent_transactions if txn.is_completed())
        
        return {
            'period_hours': hours,
            'total_transactions': total_transactions,
            'completed_transactions': completed_transactions,
            'failed_transactions': failed_transactions,
            'pending_transactions': pending_transactions,
            'success_rate': (completed_transactions / total_transactions * 100) if total_transactions > 0 else 0,
            'total_amount': total_amount,
            'total_amount_formatted': f"{total_amount / 100:.2f}元",
            'average_amount': (total_amount / completed_transactions) if completed_transactions > 0 else 0
        }
    
    def cleanup_old_transactions(self, days: int = 30) -> int:
        """
        清理旧交易记录
        
        Args:
            days: 保留天数
            
        Returns:
            清理的记录数量
        """
        cutoff_time = int(time.time()) - (days * 86400)
        
        old_transaction_ids = [
            txn_id for txn_id, txn in self.transactions.items()
            if txn.timestamp < cutoff_time
        ]
        
        for txn_id in old_transaction_ids:
            del self.transactions[txn_id]
        
        return len(old_transaction_ids)
